<?php
namespace App\Admin\Controllers\Products;

use App\Admin\Actions\Products\Material\BatchMaterialSupplierReject;
use App\Admin\Actions\Products\Material\BatchMaterialSupplierSuccess;
use App\Admin\Ajax\Products\MaterialSupplierAjax;
use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Basics\SupplierM;
use App\Models\Product\ProductMaterial;
use App\Models\Product\ProductMaterialApplicationClassify;
use App\Models\Product\ProductMaterialClassifyMax;
use App\Models\Product\ProductMaterialClassifyMin;
use App\Models\Product\ProductSupplierM;
use App\Util\RExcel;
use App\Util\User;
use Barryvdh\Snappy\Facades\SnappyPdf;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Encore\Admin\Form;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Request;

class MaterialSupplierController extends AdminController{

    protected $title = '材料说明书（已弃用）';

    protected function grid()
    {
        $grid = new Grid(new ProductSupplierM());
        $grid->model()->orderBy('id', 'DESC');
        $grid->model()->collection(function (Collection $collection){
            foreach($collection as $item) {
                $item->material_application_classify_title = $item->material->material_application_classify->title ?? '';
                $item->material_classify_max_title = $item->material->material_classify_max->title ?? '';
                $item->material_classify_min_title = $item->material->material_classify_min->title ?? '';
                $item->audit_admin_id = User::getUsernameById($item->audit_admin_id);
            }
            return $collection;
        });
        $grid->column('supplier.short_name','供应商简称');
        $grid->column('supplier.code','供应商编码');
        $grid->column('supplier_material_no','供应商材料编码');
        $grid->column('material.material_code','材料编码');
        $grid->column('material.title','材料名称');
        $grid->column('material_application_classify_title','应用品类');
        $grid->column('material_classify_max_title','材料大类');
        $grid->column('material_classify_min_title','材料小类');
        $grid->column('quote_price','报价')->display(function ($value, $column){
            if($this->audit_status != ProductSupplierM::AUDIT_SUCCESS){
                return $column->editable();
            }
            return $value;
        });
        $grid->column('quote_currency','报价单位')->display(function ($value, $column){
            if($this->audit_status != ProductSupplierM::AUDIT_SUCCESS){
                return $column->editable('select',ProductSupplierM::$_quote_currency);
            }
            return $value ? ProductSupplierM::$_quote_currency[$value] : '';
        });
        $grid->column('function','功能性')->view('products.material-supplier.function');
        $grid->column('material.test_remark','测试标准和要求');
        $grid->column('test_data','测试数据')->display(function ($value, $column){
            if($this->audit_status != ProductSupplierM::AUDIT_SUCCESS){
                return $column->editable();
            }
            return $value;
        });
        $grid->column('test_after','后整理')->display(function ($value, $column){
            if($this->audit_status != ProductSupplierM::AUDIT_SUCCESS){
                return $column->editable('select',ProductSupplierM::$_test_after);
            }
            return $value ? ProductSupplierM::$_test_after[$value] : '';
        });
        //$grid->column('composition','成分')->view('products.material-supplier.composition');
        $grid->column('composition','成分')->display(function ($value, $column){
            if($this->audit_status != ProductSupplierM::AUDIT_SUCCESS){
                return $column->editable();
            }
            return $value;
        });
        $grid->column('spec','规格参数信息')->display(function ($value, $column){
            if($this->audit_status != ProductSupplierM::AUDIT_SUCCESS){
                return $column->editable();
            }
            return $value;
        });
        $grid->column('yarn_count','纱支')->display(function ($value, $column){
            if($this->audit_status != ProductSupplierM::AUDIT_SUCCESS){
                return $column->editable();
            }
            return $value;
        });
        $grid->column('weight','克重(g/㎡)')->display(function ($value, $column){
            if($this->audit_status != ProductSupplierM::AUDIT_SUCCESS){
                return $column->editable();
            }
            return $value;
        });
        $grid->column('door_width','门幅')->display(function ($value, $column){
            if($this->audit_status != ProductSupplierM::AUDIT_SUCCESS){
                return $column->editable();
            }
            return $value;
        });
        $grid->column('door_unit','门幅单位')->display(function ($value, $column){
            if($this->audit_status != ProductSupplierM::AUDIT_SUCCESS){
                return $column->editable('select',ProductSupplierM::$_door_unit);
            }
            return $value ? ProductSupplierM::$_door_unit[$value] : '';
        });
        $grid->column('material.specification','规格');
        $grid->column('material.unit','单位');
        $grid->column('coloring_cycle','打色周期')->display(function ($value, $column){
            if($this->audit_status != ProductSupplierM::AUDIT_SUCCESS){
                return $column->editable();
            }
            return $value;
        });
        $grid->column('devlop_moq','开发MOQ（米）')->display(function ($value, $column){
            if($this->audit_status != ProductSupplierM::AUDIT_SUCCESS){
                return $column->editable();
            }
            return $value;
        });
        $grid->column('devlop_cylce','开发周期（天）')->display(function ($value, $column){
            if($this->audit_status != ProductSupplierM::AUDIT_SUCCESS){
                return $column->editable();
            }
            return $value;
        });
        $grid->column('moq','大货MOQ（米）')->display(function ($value, $column){
            if($this->audit_status != ProductSupplierM::AUDIT_SUCCESS){
                return $column->editable();
            }
            return $value;
        });
        $grid->column('cylce','大货周期（天）')->display(function ($value, $column){
            if($this->audit_status != ProductSupplierM::AUDIT_SUCCESS){
                return $column->editable();
            }
            return $value;
        });
        $grid->column('grey_cloth','坯布数量（米）')->display(function ($value, $column){
            if($this->audit_status != ProductSupplierM::AUDIT_SUCCESS){
                return $column->editable();
            }
            return $value;
        });

        $grid->column('audit_admin_id','审核人');
        $grid->column('audit_time','审核日期');
        $grid->column('audit_status','品质评审')->display(function ($value){
            return $value ? ProductSupplierM::$_auditStatus[$value] : '';
        });
        $grid->column('操作')->view('products.material-print.action');
        $grid->fixHeader();
        $grid->paginate(10);
        $grid->fixColumns(0,-2);
        $grid->disableExport();
        $grid->disableCreateButton();
        $grid->disableActions();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('products/material-supplier-download'));
        });

        $grid->batchActions(function ($batch) {
            $batch->add(new BatchMaterialSupplierSuccess());
            $batch->add(new BatchMaterialSupplierReject());
            $batch->disableDelete();
        });

        $grid->filter(function($filter){
            $filter->column(1/2, function ($filter){
                $filter->where(function ($query) {
                    $query->where('supplier_material_no', 'like', "%{$this->input}%");
                }, '查询','sku8')->placeholder('模糊查询供应商材料编码');
                $filter->equal('supplier_id', '供应商')->select(ProductSupplierM::supplierMOptions());
                $filter->equal('material.material_application_classify_id', '应用品类')->select(ProductMaterialApplicationClassify::options());
                $filter->in('audit_status', '状态')->checkbox(ProductSupplierM::$_auditStatus);
            });
            $filter->column(1/2, function ($filter) {
                $filter->equal('material_id', '材料')->select(ProductSupplierM::materialOptions());
                $filter->equal('material.material_classify_max_id', '材料大类')->select(ProductMaterialClassifyMax::options());
                $filter->equal('material.material_classify_min_id', '材料小类')->select(ProductMaterialClassifyMin::options());
                $filter->equal('audit_admin_id','审核人')->select(User::getMUserOptions());
            });
        });
        return $grid;
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new MaterialSupplierAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function modal(){
        $action = request('action');
        $param = request('param');
        $modal = new MaterialSupplierAjax();
        return $param ? call_user_func([$modal,$action],$param) : call_user_func([$modal,$action]);
    }

    protected function form(){
        $form = new Form(new ProductSupplierM());
        $form->hidden('id');
        $form->select('material_id','材料编码')->options(ProductMaterial::options())->rules('required')->readonly()->help('材料名称规则：材质+规格+工艺（功能）');
        $form->select('title','材料名称')->rules('required')->readonly()->help('材料名称规则：材质+规格+工艺（功能）');
        $form->select('supplier_id','供应商')->options(SupplierM::options())->rules('required')->readonly();
        if ($form->isEditing()) {
            $form->text('supplier_material_no','供应商材料编号')->rules('required')->required();
            $form->text('container_no','柜号');
            $form->decimal('quote_price','报价');
            $form->select('quote_currency','报价单位')->options(ProductSupplierM::$_quote_currency);
            $form->multipleSelect('function','功能性')->options(ProductSupplierM::$_function);

            $form->text('test_data','测试数据');
            $form->switch('audit_status', '是否评审')->states(statusSwitch())->default(ProductSupplierM::$_auditStatus);
            $form->select('test_after','后整理')->options(ProductSupplierM::$_test_after);

            $form->text('composition','成分');
            //$form->table('composition','成分',function($table){
            //    $table->text('ratio','成分占比')->width(5);
            //    $table->select('type','成分单位')->options(ProductSupplierM::$_composition)->width(5);
            //});

            $form->text('spec','材料规格参数');
            $form->text('yarn_count','纱支');
            $form->number('weight','克重(g/㎡)')->min(0)->width(5);
            $form->number('door_width','门幅')->min(0)->width(5);
            $form->select('door_unit','门幅单位')->options(ProductSupplierM::$_door_unit);
            $form->number('coloring_cycle','打色周期')->min(0)->width(5);
            $form->number('devlop_moq','开发MOQ（米）')->min(0)->width(5);
            $form->number('devlop_cylce','开发周期（天）')->min(0)->width(5);
            $form->number('moq','大货MOQ（米）')->min(0)->width(5);
            $form->number('cylce','大货周期（天）')->min(0)->width(5);
            $form->number('grey_cloth','坯布数量（米）')->min(0)->width(5);
        }

        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
            $tools->disableView();
        });
        return $form;
    }

    protected function printFile()
    {
        $id = request('id');
        $model = ProductSupplierM::query()->find($id);
        if (!$model) {
            admin_toastr('数据异常！','error');
            return back();
        }
        try{
            $filePath = ProductSupplierM::getFile($model->supplier->code,$model->material->material_code);
            //文件不存在，则新建
            if (!file_exists($filePath)) {
                $pdf = SnappyPdf::loadView('products.material-print.index',compact('id','model'));
                $pdf->save($filePath);
            }
            if(!file_exists($filePath)){
                admin_toastr('无文件！','error');
                return back();
            }
            return response()->file($filePath);
        }catch (\Exception $e){
            report($e);
            admin_toastr('操作失败！','error');
            return back();
        }
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = ProductSupplierM::query()->orderBy('id', 'DESC');
        foreach ($filters as $key => $_filter){
            if($key == 'sku8'){
                $query->where(function ($query) use($_filter){
                    $query->where('supplier_material_no', 'like', "%{$_filter}%");
                });
            }
            if($key == 'audit_status'){
                $query->whereIn($key,$_filter);
            }
            if(in_array($key,['supplier_id', 'material_id', 'audit_admin_id'])){
                $query->where($key,$_filter);
            }
            if($key == 'material'){
                $query->whereHas('material', function ($query) use($_filter){
                    foreach ($_filter as $_key => $__filter){
                        if(in_array($_key,[
                            'material_application_classify_id',
                            'material_classify_max_id',
                            'material_classify_min_id',
                        ])){
                            $query->where($_key,$__filter);
                        }
                    }
                });
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        $head = ['供应商名称','供应商编码','供应商材料编号','材料编号','材料名称','应用大类','应用小类','材料大类','材料中类','材料小类',
            '报价','报价单位','功能性','测试标准和要求','测试数据','后整理','成分','纱支','克重(g/㎡)','门幅','门幅单位','规格','单位',
            '打色周期','开发MOQ（米）','开发周期（天）','大货MOQ（米）','大货周期（天）','坯布数量（米）',
            '审核状态','审核人','审核日期'];
        RExcel::exportCsv('材料供应商',function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    public static function getDownloadData($res)
    {
        foreach ($res as $model){

            //功能性
            $functionStr = '';
            if ($model->function) {
                $functionStr = implode(',', $model->function);
            }
            //成分
            $compositionStr = '';
            if ($model->composition) {
                $data = [];
                foreach ($model->composition as $key => $val){
                    $data[$key] = $val['ratio'].ProductSupplierM::$_composition[$val['type']];
                }
                $compositionStr = implode(',', $data);
            }
            $temp = [
                $model->supplier->short_name ?? '',
                $model->supplier->code ?? '',
                $model->supplier_material_no ?? '',
                $model->material->material_code ?? '',
                $model->material->title ?? '',
                $model->material->material_application_classify->title ?? '',
                $model->material->material_classify_max->title ?? '',
                $model->material->material_classify_min->title ?? '',
                $model->quote_price ?? '',
                $model->quote_currency ? ProductSupplierM::$_quote_currency[$model->quote_currency] : '',
                $functionStr,
                $model->material->test_remark ?? '',
                $model->test_data ?: '',
                $model->test_after ? ProductSupplierM::$_test_after[$model->test_after] : '',
                $compositionStr,
                $model->yarn_count ?: '',
                $model->weight ?: '',
                $model->door_width ?: '',
                $model->door_unit ?: '',
                $model->material->specification ?? '',
                $model->material->unit ?? '',
                $model->coloring_cycle ?: '',
                $model->devlop_moq ?: '',
                $model->devlop_cylce ?: '',
                $model->moq ?: '',
                $model->cylce ?: '',
                $model->grey_cloth ?: '',
                $model->audit_status ? ProductSupplierM::$_auditStatus[$model->audit_status] : '',
                $model->audit_admin_id ? User::getUsernameById($model->audit_admin_id) : '',
                $model->audit_time ?: '',
            ];
            yield $temp;
        }
    }

}
